import type { BillId } from "./interface";
import service from "../common/service";
import useService from '@/hooks/useService';
const useBillId = (config ?: { isBillVar ?: boolean }) => {
	const { isBillVar } = config || {};
	const mainService = useService({ prefix: "mainApi" });
	/**
	 * @description
	 * @param
	 */
	const getBillIdVar = async (billId : BillId, data : Object, billName : string) => {
		const res = await mainService.request('单据号生成规则设置', 'GetEnjoyBillVar', billName);
		if (res !== '变量') {
			billId.BillVariable = data[res] || billId?.BillVariable || '';
		}
		else {
			billId.BillVariable = '';
		}
		return true;
	}

	const getBillId = async (billId : BillId,) => {

		const res = await mainService.request('单号生成服务', 'EnjoyGetBillId', billId);
		if (res) {
			return res;
		}
		else {
			return '';
		}
	}

	/**
	 * @description       生成单据号
	 * @param billId
	 * @param data
	 * @param uniqueKey
	 */
	const createBillId = async (billId : BillId, data : Object, billName : string) => {
		const cloneBillId = billId;
		const flag = await getBillIdVar(cloneBillId, data, billName);

		//获取单据号变量出现异常
		if (!flag) {
			return { flag: false, message: '' };
		}

		const ret = await getBillId(cloneBillId);
		if (!ret) {
			uni.showToast({
				duration: 2000,
				icon: 'none',
				title: '生成单据号错误:没有获取到单据号！',
				mask: true,
			});
			return {message:'生成单据号错误:没有获取到单据号！'};
		}
		else {
			var newBillId = ret;
			const { idField } = { idField: 'c_id' };
			if (cloneBillId) {
				cloneBillId.BillIdKeyValue = { key: idField, value: newBillId };
			}
			
			return { billId: newBillId };
		}
	}

	return { createBillId };
};

export default useBillId;